// pages/userInfo/collection/collection.js
const app = getApp()
import api from '../../../config/api'
import path from '../../../config/path'
const { $Message } = require('../../../dist/base/index');
const { $Toast } = require('../../../dist/base/index');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    picLocal: app.globalData.picLocal,
    baseHeadPic: app.globalData.picLocal + "/default/head/head.png",
    houseList: [],
    pageData: {
      pageNo: 1,
      pageSize: 10,
      count: 0
    },
    bottomLoading: false,
    loading: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: '我的收藏',
    })
    this.fetchCollections(true)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.bottomStart();
    if (this.data.houseList.length >= this.data.pageData.count && this.data.pageData.count !== 0) {
      $Toast({
        content: '没有更多数据了'
      })
      this.bottomEnd();
      return;
    }
    this.data.pageData.pageNo++;
    this.setData({
      pageData: this.data.pageData
    })
    this.fetchCollections(false)
  },

  toHouseInfo(e) {
    const houseId = e.currentTarget.dataset.id
    if (!houseId) {
      $Toast({ content: '房源信息有误' })
      return
    }
    wx.navigateTo({
      url: '../../index/houseInfo/houseInfo?id=' + houseId,
    })
  },

  // 底部加载
  bottomStart() {
    this.setData({
      bottomLoading: true
    })
  },

  // 底部不加载
  bottomEnd() {
    this.setData({
      bottomLoading: false
    })
  },

  // 获取收藏列表并获取房源详情
  async fetchCollections(reset) {
    const { pageNo, pageSize } = this.data.pageData
    
    try {
      // 获取收藏列表
      const res = await api.get('house', `${path.path.getMyCollections}?pageNo=${pageNo}&pageSize=${pageSize}`)
      const page = res.data || {}
      const collectionList = page.records || page.list || []
      const total = page.total || page.count || collectionList.length

      // 如果没有收藏数据
      if (collectionList.length === 0) {
        this.setData({
          houseList: [],
          pageData: {
            ...this.data.pageData,
            count: total
          },
          loading: false
        })
        return
      }

      // 获取每个收藏房源的详细信息
      const houseDetails = await this.fetchHouseDetails(collectionList)
      
      this.setData({
        houseList: reset ? houseDetails : this.data.houseList.concat(houseDetails),
        pageData: {
          ...this.data.pageData,
          count: total
        },
        loading: false
      })
      
    } catch (err) {
      console.log('获取收藏列表失败:', err)
      $Toast({ content: '加载失败' })
      this.setData({ loading: false })
    } finally {
      this.bottomEnd()
    }
  },

  // 获取房源详细信息
  async fetchHouseDetails(collectionList) {
    const houseDetails = []
    
    for (const collection of collectionList) {
      try {
        // 获取房源详情
        const houseRes = await api.get('house', path.path.getHouseDetail + collection.houseId)
        if (houseRes.code === 200 && houseRes.data) {
          const houseInfo = this.normalizeHouseInfo(houseRes.data)
          houseDetails.push(houseInfo)
        }
      } catch (err) {
        console.log(`获取房源 ${collection.houseId} 详情失败:`, err)
        // 即使获取详情失败，也添加一个基本的信息对象
        houseDetails.push({
          id: collection.houseId,
          title: '房源信息加载中...',
          price: 0,
          roomType: '未知',
          area: '--',
          province: '',
          city: '',
          district: '',
          address: '',
          picList: []
        })
      }
    }
    
    return houseDetails
  },

  // 标准化房源信息
  normalizeHouseInfo(houseData) {
    // 解析设施信息
    let facilities = []
    try {
      facilities = houseData.facilities ? JSON.parse(houseData.facilities) : []
    } catch (e) {
      facilities = []
    }

    return {
      id: houseData.id,
      title: houseData.title || '暂无标题',
      price: houseData.price || 0,
      description: houseData.description || '',
      roomType: houseData.roomType || '',
      province: houseData.province || '',
      city: houseData.city || '',
      district: houseData.district || '',
      address: houseData.address || '',
      area: houseData.area || '--',
      picList: (houseData.picList || []).map(pic => ({
        url: pic.url || pic.path || pic
      })),
      facilities: facilities,
      orientation: houseData.orientation || '未知',
      floor: houseData.floor || '--',
      totalFloor: houseData.totalFloor || '--',
      decoration: houseData.decoration || '未知'
    }
  }
})